request = require 'request'
db = require '../utils/connect'
async = require 'async'
fs = require 'fs'
Article = require '../models/article'
log = require '../utils/log'

crawAppmsgs = (account,done)->
	db.queryOne 'select uin,`key` from cookie',(err, result)->
		key = result.key
		uin = result.uin

		biz = new Buffer(account.uin.toString()).toString('base64')
		historyUrl = 'http://mp.weixin.qq.com/mp/getmasssendmsg?__biz='+biz+'&uin='+uin+'&key='+key+'&count=200&f=json'

		request.get historyUrl, (err, res, body)->
			console.log err if err
			try
				body = JSON.parse body
			catch e
				console.log e 
				return done null
			unless body?.general_msg_list?.list?.length>0
				return done null
			log.error body?.general_msg_list?.list?.length
			async.forEachSeries body.general_msg_list.list, (appmsg, cb)->
				sql = "insert ignore into appmsgs (fakeid, mid, datetime,json,type) values (?,?,?,?,?)"
				db.runSql sql , [appmsg.comm_msg_info.fakeid, appmsg.comm_msg_info.id, new Date(appmsg.comm_msg_info.datetime*1000), JSON.stringify(appmsg.app_msg_ext_info),appmsg.comm_msg_info.type], cb
			,(err)->
				console.log err if err
				done null

crawDetail = (done)->
	sql = "select *,appmsgs.id as mid from appmsgs join accounts on  appmsgs.state = 0 and appmsgs.type = 49 and appmsgs.fakeid = accounts.uin "
	db.runSql sql , (err, result)->
		done err if err
		async.forEachSeries result, (appmsg , callback)->
			try
				appmsg.json = JSON.parse appmsg.json
			catch e
				console.log e
				return callback null
			articles = []
			articles.push
				contenturl: appmsg.json.content_url
				cover: appmsg.json.cover
				digest: appmsg.json.digest
				fileid: appmsg.json.fileid
				sourceurl: appmsg.json.source_url
				title: appmsg.json.title
				nickname: appmsg.nickname
				username: appmsg.username
				datetime: appmsg.datetime

			if appmsg.json.is_multi
				appmsg.json.multi_app_msg_item_list.forEach (item)->
					articles.push
						contenturl: item.content_url
						cover: item.cover
						digest: item.digest
						fileid: item.fileid
						sourceurl: item.source_url
						title: item.title
						nickname: appmsg.nickname
						username: appmsg.username
						datetime: appmsg.datetime

			async.forEachSeries articles, (article, cb)->
				sql = "insert ignore into articles set ?"
				db.runSql sql, article, cb
			,callback
		,done

autoApprove = (done)->
	sql = "select articles.* from articles join accounts on accounts.active = 1 and accounts.username = articles.username and articles.state=0 and articles.datetime > '2013-09-14'"

	db.runSql sql, (err, result)->
		async.forEachSeries result, (article,cb)->
			Article.approve article.id, (err)->
				if err 
					log.error err if err
					return cb null
				sql = "update appmsgs set state = 1 where id = ? "
				db.runSql sql, [appmsg.mid], (err)->
					cb err
		,done


# getHearimg = (done)->
# 	sql = "select * from accounts where active = 1"
# 	db.runSql sql, (err, result)->
# 		return done err if err
# 		jar = request.jar()
# 		cookies = "o_cookie=719557509; pgv_pvid=3015879784; ptui_loginuin=369600584@qq.com; ptcz=999ddb8b8111a23d6d2b7d130e4781f0b1e68db673ee2fb53a81faaae4d79788; pt2gguin=o0369600584; ptisp=cnc; webwxuvid=780126216; wxuin=641130260; wxsid=STr3UCGVVdRC0iE/; wxstaytime=1376831789; mm_lang=zh_CN; wxpluginkey=1376819849"
# 		for a in cookies.split ';'
# 			cookie = request.cookie a
# 			jar.add(cookie)

# 		async.forEachSeries result, (account, cb)->
# 			url = 'http://wx.qq.com'+ account.headimgurl
# 			ws = fs.createWriteStream '../public/images/'+account.username+'.jpg'
# 			request({url,jar},cb).pipe(ws)
# 		,done

run = (done)->
	sql = "select * from accounts where active = 1"
	db.runSql sql, (err, result)->
		async.forEachLimit result,5, crawAppmsgs, (err)->
			console.log err if err
		,(err)->
			console.log err if err
	crawDetail (err)->
		log.error err if err

	autoApprove (err)->
		log.error err if err
		
	setTimeout run, 1000*60*5 
run()
process.on 'uncaughtException',(err)->
	log.error err if err
# async.series [run,crawDetail,crawContent]
